package atguigu.time;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;  
import java.util.concurrent.TimeUnit;  
  
public class CountdownTimer {  
  
    private int totalSeconds;

    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();  
  
    public CountdownTimer(int totalSeconds) {  
        this.totalSeconds = totalSeconds;  
    }  
  
    public void start() {  
        // 使用Runnable和scheduleAtFixedRate来实现每秒更新  
        Runnable countdownTask = () -> {  
            totalSeconds--;  
            if (totalSeconds > 0) {  
                System.out.println("剩余时间: " + totalSeconds + " 秒");  
            } else {  
                // 当倒计时结束时，关闭ExecutorService  
                scheduler.shutdown();  
                System.out.println("倒计时结束！");  
            }  
        };  
  
        // 初始延迟为0秒，之后每隔1秒执行一次  
        scheduler.scheduleAtFixedRate(countdownTask, 0, 1, TimeUnit.SECONDS);  
    }  
  
    public static void main(String[] args) {  
        // 创建一个倒计时实例，总时间为10秒  
        CountdownTimer timer = new CountdownTimer(10);  
        // 开始倒计时  
        timer.start();  
    }  
}